﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Crosland.Automotriz.Facade.Interface;
using Crosland.Automotriz.Facade.Facade;
using Crosland.Automotriz.Entidad;
using Microsoft.Reporting.WebForms;
using System.Configuration;
using System.Security.Principal;
using System.Net;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using Crosland.Automotriz.Core;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using System.Threading;


namespace Crosland.Automotriz.Web.Vehiculos
{
    public partial class wFrmImpresionCartaMPCartaT :BaseForm
    {
        string idNegocio = ConfigurationManager.AppSettings["Negocio"];

        iFacadeCompensacionVehiculo BL_CompensacionVehiculo = new FacadeCompensacionVehiculo();

        protected override void Inicializar()
        {
            ddlAnio.Value = DateTime.Today.Year;
            ddlAnioEmision.Value = DateTime.Today.Year;
            ddlMes.SelectedIndex = DateTime.Today.Month;

            ddlRepreLegal.DataSource = BL_CompensacionVehiculo.ListarRepresentantes();
            ddlRepreLegal.DataBind();
            ddlRepreLegal.SelectedIndex = 0;

            Panel img = (Panel)Master.FindControl("asp");
            img.Visible = false;
        }
     
        protected void BuscarFacturas()
        {
            int anio_operacion = Convert.ToInt32(ddlAnio.Value);
            int mes_operacion = Convert.ToInt32(ddlMes.Value);
            int indicador = Convert.ToInt32(ddlFiltroDoc.Value);
            int anio_facturacion = Convert.ToInt32(ddlAnioEmision.Value);

            List<TD_Facturas_Impresion> Lista;
            Lista = BL_CompensacionVehiculo.ListarFacturasImpresion(anio_operacion, mes_operacion, indicador, anio_facturacion);
            grdFacturas.DataSource = Lista;
            grdFacturas.DataBind();
        }

        protected void btnConsultar_Click(object sender, EventArgs e)
        {
            BuscarFacturas();
        }

        protected void btnImprimir_Click(object sender, EventArgs e)
        {
            int indi = 0;
            List<object> fieldValues = grdFacturas.GetSelectedFieldValues(new string[] { "NRO_FACTURA", "IND_IMPR_CMP", "IND_IMPR_CT" });
            if (fieldValues == null) { return; }
            if (fieldValues.Count == 0) { return; }


            foreach (object[] item in fieldValues)
            {
                indi = indi + 1;
            }

            int factura = SeleccionActual();
            int representante = Convert.ToInt32(ddlRepreLegal.Value);

            if (Convert.ToInt32(ddlFiltroDoc.SelectedIndex) == 0)
            {
                if (rbImpresion.SelectedIndex > -1)
                {
                    if (indi > 0)
                    {
                        if (rbImpresion.SelectedItem.Value.ToString() == "1")//Registro Actual
                        {

                            if (factura > 0)
                            {
                                Session["FacturaVehiculo"] = factura;
                                Session["RL"] = representante;

                                string script = "ShowImpresion();";
                                ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", script, true);
                            }
                            else
                            {
                                lblValidacion.Text = "Las factura seleccionada ya se imprimió.";
                                string script = "ShowValidacion();";
                                ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", script, true);
                            }


                        }
                        else if (rbImpresion.SelectedItem.Value.ToString() == "0")//Todo
                        {
                            List<object> valores = grdFacturas.GetSelectedFieldValues(new string[] { "NRO_FACTURA", "IND_IMPR_CMP", "IND_IMPR_CT", "NRO_POLIZA", "NRO_TITULO" });
                            foreach (object[] item in valores)
                            {
                                int facturaTodos = int.Parse(item[0].ToString());
                                bool cmp = Convert.ToBoolean(item[1]);
                                bool ct = Convert.ToBoolean(item[2]);

                                string NRO_POLIZA = "";
                                string NRO_TITULO = "";

                                if (item[3] == null) { NRO_POLIZA = ""; } else { NRO_POLIZA = item[3].ToString(); }
                                if (item[4] == null) { NRO_TITULO = ""; } else { NRO_TITULO = item[4].ToString(); }

                                if (cmp == false)
                                {
                                    //imprimir Carta Medio de Pago

                                    ExportToEMF_CMP(facturaTodos, representante);
                                    Print();

                                    T_VEN_CARTAS_VEH_IMPRESION entity = new T_VEN_CARTAS_VEH_IMPRESION();
                                    entity.ID_ORG_VTA = 3;
                                    entity.ID_OFI_VTA = 17;
                                    entity.NRO_FACTURA = facturaTodos;
                                    entity.IND_IMPR_CMP = 1;
                                    entity.IND_IMPR_CT = null;
                                    entity.FEC_IMPRESION_CMP = DateTime.Now;
                                    entity.FEC_IMPRESION_CT = null;
                                    BL_CompensacionVehiculo.GuardarImpresionCMPCT(entity);
                                }
                                if (ct == false)
                                {
                                    if (string.IsNullOrEmpty(NRO_POLIZA) || string.IsNullOrEmpty(NRO_TITULO)) { }
                                    else
                                    {
                                        //imprimir Carta Título

                                        ExportToEMF_CT(facturaTodos, representante);
                                        Print();

                                        T_VEN_CARTAS_VEH_IMPRESION entity = new T_VEN_CARTAS_VEH_IMPRESION();
                                        entity.ID_ORG_VTA = 3;
                                        entity.ID_OFI_VTA = 17;
                                        entity.NRO_FACTURA = facturaTodos;
                                        entity.IND_IMPR_CMP = null;
                                        entity.IND_IMPR_CT = 1;
                                        entity.FEC_IMPRESION_CMP = null;
                                        entity.FEC_IMPRESION_CT = DateTime.Now;
                                        BL_CompensacionVehiculo.GuardarImpresionCMPCT(entity);
                                    }
                                }
                            }

                            QuitarSeleccionGrilla();
                            //BuscarFacturas();
                        }
                    }
                    else
                    {
                        lblValidacion.Text = "Por favor seleccione facturas a imprimir.";
                        string script = "ShowValidacion();";
                        ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", script, true);
                    }

                }
                else
                {
                    lblValidacion.Text = "Por favor seleccione un tipo de impresion.";
                    string script = "ShowValidacion();";
                    ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", script, true);
                }

            }
            else
            {
                int facturaReimpresion = SeleccionActualSinValidacion();
                
                Session["FacturaVehiculo"] = facturaReimpresion;
                Session["RL"] = representante;

                string script = "ShowImpresion();";
                ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", script, true);
              
            }


           
        }

        protected void AbrirPdf()
        {
            
            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            
            Response.AddHeader("Content-Disposition", "attachment; filename=PDF_IMPRESION_CT_CMP.pdf");
            Response.ContentType = "application/pdf";
            Response.TransmitFile(ConfigurationManager.AppSettings["RutaPdfImpresion"] + "/PDF_IMPRESION_CT_CMP.pdf");
            Response.End();
            

        }

        protected List<int> CargarFacturasSeleccionadas()
        {
            List<int> facturas = new List<int>();
            List<object> fieldValues = grdFacturas.GetSelectedFieldValues(new string[] { "NRO_FACTURA", "IND_IMPR_CMP", "IND_IMPR_CT" });
            foreach (object[] item in fieldValues)
            {
                bool cmp = Convert.ToBoolean(item[1]);
                bool ct = Convert.ToBoolean(item[2]);
                int dato =Convert.ToInt32(item[0]);

                if (cmp == true && ct == true)
                {}
                else
                {
                    facturas.Add(dato);
                }
               

                
            }

            return facturas;
        }

        protected int SeleccionActual()
        {
            int factura = 0;
            string titulo = string.Empty;
            string poliza = string.Empty;

            bool cmp = Convert.ToBoolean(grdFacturas.GetRowValues(grdFacturas.FocusedRowIndex, "IND_IMPR_CMP"));
            bool ct = Convert.ToBoolean(grdFacturas.GetRowValues(grdFacturas.FocusedRowIndex, "IND_IMPR_CT"));

            //Session["CMP"] = cmp;
            //Session["CT"] = ct;

            if (cmp == true && ct == true)
            {
                factura = 0;
            }
            else
            {
                factura = Convert.ToInt32(grdFacturas.GetRowValues(grdFacturas.FocusedRowIndex, "NRO_FACTURA"));
                List<TD_FACTURA_CONSULTA> ListaConsulta = BL_CompensacionVehiculo.ListarConsultaFactura(factura);

                if (!String.IsNullOrEmpty(ListaConsulta[0].NRO_POLIZA))
                {
                    poliza = ListaConsulta[0].NRO_POLIZA;
                }
                else
                {
                    poliza = string.Empty;
                }
                
                if(!String.IsNullOrEmpty(ListaConsulta[0].NRO_TITULO))
                {
                    titulo = ListaConsulta[0].NRO_TITULO;
                }
                else
                {
                    titulo = string.Empty;
                }


            }


            Session["Titulo"] = titulo;
            Session["Poliza"] = poliza;

            return factura;
        }

        protected int SeleccionActualSinValidacion()
        {
            int factura = 0;
            string titulo = string.Empty;
            string poliza = string.Empty;

            bool cmp = Convert.ToBoolean(grdFacturas.GetRowValues(grdFacturas.FocusedRowIndex, "IND_IMPR_CMP"));
            bool ct = Convert.ToBoolean(grdFacturas.GetRowValues(grdFacturas.FocusedRowIndex, "IND_IMPR_CT"));

            //Session["CMP"] = cmp;
            //Session["CT"] = ct;

                factura = Convert.ToInt32(grdFacturas.GetRowValues(grdFacturas.FocusedRowIndex, "NRO_FACTURA"));
                List<TD_FACTURA_CONSULTA> ListaConsulta = BL_CompensacionVehiculo.ListarConsultaFactura(factura);

                if (!String.IsNullOrEmpty(ListaConsulta[0].NRO_POLIZA))
                {
                    poliza = ListaConsulta[0].NRO_POLIZA;
                }
                else
                {
                    poliza = string.Empty;
                }

                if (!String.IsNullOrEmpty(ListaConsulta[0].NRO_TITULO))
                {
                    titulo = ListaConsulta[0].NRO_TITULO;
                }
                else
                {
                    titulo = string.Empty;
                }
             
            Session["Titulo"] = titulo;
            Session["Poliza"] = poliza;

            return factura;
        }

        protected void btnAceptar_Click(object sender, EventArgs e)
        {
            if (rbReporte.SelectedIndex > -1) 
            {

                if (rbReporte.SelectedItem.Value.ToString() == "1")
                {
                    Session["Indicador"] = "1";
                    CargarCMPSeleccionActual();
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowCMP", String.Format("ShowCMP()"), true);
                }
                else if (rbReporte.SelectedItem.Value.ToString() == "2")
                {
                    Session["Indicador"] = "2";
                    string titulo = Session["Titulo"].ToString();
                    string poliza = Session["Poliza"].ToString();

                    if (string.IsNullOrEmpty(titulo) || string.IsNullOrEmpty(poliza))
                    {
                        lblValidacion.Text = "Para imprimir la carta titulo se necesita Nro.Poliza y Nro.Titulo.";
                        string script = "ShowValidacion();";
                        ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", script, true);
                    }
                    else
                    {
                        CargarCTSeleccionActual();
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowCT", String.Format("ShowCT()"), true);
                    }
                }


            }
        }

        [Serializable]
        public sealed class RSCredentials : IReportServerCredentials
        {
            public WindowsIdentity ImpersonationUser
            {
                get { return null; }
            }

            public ICredentials NetworkCredentials
            {
                get
                {
                    string userName = ConfigurationManager.AppSettings[DatosConfiguracion.RsUser];
                    string password = ConfigurationManager.AppSettings[DatosConfiguracion.RsPassword];
                    string domain = ConfigurationManager.AppSettings[DatosConfiguracion.RsDomain];

                    return new NetworkCredential(userName, password, domain);
                }
            }

            public bool GetFormsCredentials(out Cookie authCookie, out String userName, out String password,
                out String authority)
            {
                authCookie = null;
                userName = null;
                password = null;
                authority = null;
                return false;
            }
        }

        private static int m_nCurrentPageIndex;

        private static IList<Stream> m_streams = new List<Stream>();
        private static byte[] bt;

        private static void ExportToEMF_CMP(int factura, int representante)
        {

            // initialize ReportViewer
            ReportViewer rptViewer = new ReportViewer();
            rptViewer.ServerReport.ReportServerCredentials = new RSCredentials();
            rptViewer.ServerReport.ReportServerUrl = new Uri(ConfigurationManager.AppSettings[DatosConfiguracion.RsServer]);
            rptViewer.ServerReport.ReportPath = "/SAP_Vehiculos/rs_CartaMedioPago";

            ReportParameter parameter = new ReportParameter("FACTURA", factura.ToString());
            ReportParameter parameter2 = new ReportParameter("Representante", representante.ToString());

            rptViewer.ServerReport.SetParameters(parameter);
            rptViewer.ServerReport.SetParameters(parameter2);

            rptViewer.ProcessingMode = ProcessingMode.Remote;

            ServerReport report = rptViewer.ServerReport;

            // print
            string sExtension;
            string sEncoding;
            string sMimeType;
            string[] sStreamIds;
            Warning[] warnings;

            // render into EMF -- one page per one stream
            // render first page and get streamIds for the rest pages
            //byte[] 
            bt = report.Render("Image"
            , GetDeviceInfo()
            , out sMimeType
            , out sEncoding
            , out sExtension
            , out sStreamIds
            , out warnings);
            SaveToStream(bt);

            // iterate through each streamId and save
            foreach (string sStreamId in sStreamIds)
            {
                bt = report.RenderStream("Image", sStreamId, GetDeviceInfo(), out sMimeType, out sEncoding);
                SaveToStream(bt);
            }

            // set stream positions to 0
            foreach (Stream stream in m_streams)
                stream.Position = 0;

           

        }

        private static void ExportToEMF_CT(int factura, int representante)
        {

            // initialize ReportViewer
            ReportViewer rptViewer = new ReportViewer();
            rptViewer.ServerReport.ReportServerCredentials = new RSCredentials();
            rptViewer.ServerReport.ReportServerUrl = new Uri(ConfigurationManager.AppSettings[DatosConfiguracion.RsServer]);
            rptViewer.ServerReport.ReportPath = "/SAP_Vehiculos/rs_Carta.Titulo";

            ReportParameter parameter = new ReportParameter("FACTURA", factura.ToString());
            ReportParameter parameter2 = new ReportParameter("Representante", representante.ToString());

            rptViewer.ServerReport.SetParameters(parameter);
            rptViewer.ServerReport.SetParameters(parameter2);

            rptViewer.ProcessingMode = ProcessingMode.Remote;
            ServerReport report = rptViewer.ServerReport;
            // print
            string sExtension;
            string sEncoding;
            string sMimeType;
            string[] sStreamIds;
            Warning[] warnings;

            // render into EMF -- one page per one stream
            // render first page and get streamIds for the rest pages
            //byte[] 
            bt = report.Render("Image"
            , GetDeviceInfo()
            , out sMimeType
            , out sEncoding
            , out sExtension
            , out sStreamIds
            , out warnings);
            SaveToStream(bt);

            // iterate through each streamId and save
            foreach (string sStreamId in sStreamIds)
            {
                bt = report.RenderStream("Image", sStreamId, GetDeviceInfo(), out sMimeType, out sEncoding);
                SaveToStream(bt);
            }

            // set stream positions to 0
            foreach (Stream stream in m_streams)
                stream.Position = 0;

        }

        private static void SaveToStream(byte[] bStr)
        {
            Stream fs = new MemoryStream();
            fs.Write(bStr, 0, bStr.Length);
            m_streams.Add(fs);
        }

        private static void Print()
        {
            // print document
            if (m_streams == null || m_streams.Count == 0)
                return;

            PrintDocument printDoc = new PrintDocument();
            if (!printDoc.PrinterSettings.IsValid)
            {
                Console.WriteLine("Can't find printer");
                return;
            }

            printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
            printDoc.Print();
        }

        public static System.Drawing.Image ConvertirAImagen(byte[] byteArrayIn)
        {
            System.Drawing.Image returnImage = System.Drawing.Image.FromStream(new MemoryStream(byteArrayIn));
            return returnImage;

        }

        private static string GetDeviceInfo()
        {
            return "<DeviceInfo>"
            + " <OutputFormat>EMF</OutputFormat>"
            + " <StartPage>1</StartPage>"
            + " <EndPage>1</EndPage>"
            + " <PageWidth>8.5in</PageWidth>"
            + " <PageHeight>11in</PageHeight>"
            + " <MarginTop>0.25in</MarginTop>"
            + " <MarginLeft>0.25in</MarginLeft>"
            + " <MarginRight>0.25in</MarginRight>"
            + " <MarginBottom>0.25in</MarginBottom>"
            + "</DeviceInfo>";
        }

        private static void PrintPage(object sender, PrintPageEventArgs ev)
        {
            Metafile pageImage = new Metafile(m_streams[m_nCurrentPageIndex]);
            ev.Graphics.DrawImage(pageImage, ev.PageBounds);

            m_nCurrentPageIndex++;
            ev.HasMorePages = (m_nCurrentPageIndex < m_streams.Count);
        }

        protected void CargarCMPSeleccionActual()
        {
            int factura = Convert.ToInt32(Session["FacturaVehiculo"]);
            int representante = Convert.ToInt32(Session["RL"]);

            this.rvPopupReporte.ShowPrintButton = false;//Oculta el boton imprimir

            this.rvPopupReporte.ProcessingMode = ProcessingMode.Remote;
            this.rvPopupReporte.ShowCredentialPrompts = true;
            this.rvPopupReporte.ShowExportControls = true;
            this.rvPopupReporte.ServerReport.ReportServerCredentials = new RSCredentials();
            this.rvPopupReporte.ServerReport.ReportServerUrl =
                new Uri(ConfigurationManager.AppSettings[DatosConfiguracion.RsServer]);
            this.rvPopupReporte.ServerReport.ReportPath = "/SAP_Vehiculos/rs_CartaMedioPago";

            ReportParameter parameter = new ReportParameter("FACTURA", factura.ToString());
            ReportParameter parameter2 = new ReportParameter("Representante", representante.ToString());

            this.rvPopupReporte.ServerReport.SetParameters(parameter);
            this.rvPopupReporte.ServerReport.SetParameters(parameter2);
        }

        protected void CargarCTSeleccionActual()
        {
            int factura = Convert.ToInt32(Session["FacturaVehiculo"]);
            int representante = Convert.ToInt32(Session["RL"]);

            this.rvPopupReporte.ShowPrintButton = false;//oculta el boton imprimir

            this.rvPopupReporte.ProcessingMode = ProcessingMode.Remote;
            this.rvPopupReporte.ShowCredentialPrompts = true;
            this.rvPopupReporte.ShowExportControls = true;
            this.rvPopupReporte.ServerReport.ReportServerCredentials = new RSCredentials();
            this.rvPopupReporte.ServerReport.ReportServerUrl =
                new Uri(ConfigurationManager.AppSettings[DatosConfiguracion.RsServer]);
            this.rvPopupReporte.ServerReport.ReportPath = "/SAP_Vehiculos/rs_Carta.Titulo";

            ReportParameter parameter = new ReportParameter("FACTURA", factura.ToString());
            ReportParameter parameter2 = new ReportParameter("Representante", representante.ToString());

            this.rvPopupReporte.ServerReport.SetParameters(parameter);
            this.rvPopupReporte.ServerReport.SetParameters(parameter2);
        }

        protected void btnImprimirCMP_Click(object sender, EventArgs e)
        {
            string indicador = Session["Indicador"].ToString();

            if (indicador == "1")
            {
                T_VEN_CARTAS_VEH_IMPRESION entity = new T_VEN_CARTAS_VEH_IMPRESION();

                entity.ID_ORG_VTA = 3;
                entity.ID_OFI_VTA = 17;
                entity.NRO_FACTURA = Convert.ToInt32(Session["FacturaVehiculo"]);
                entity.IND_IMPR_CMP = 1;
                entity.IND_IMPR_CT = null;
                entity.FEC_IMPRESION_CMP = DateTime.Now;
                entity.FEC_IMPRESION_CT = null;

                BL_CompensacionVehiculo.GuardarImpresionCMPCT(entity);
                QuitarSeleccionGrilla();
                BuscarFacturas();
            }
            else if(indicador=="2")
            {
                T_VEN_CARTAS_VEH_IMPRESION entity = new T_VEN_CARTAS_VEH_IMPRESION();

                entity.ID_ORG_VTA = 3;
                entity.ID_OFI_VTA = 17;
                entity.NRO_FACTURA = Convert.ToInt32(Session["FacturaVehiculo"]);
                entity.IND_IMPR_CMP = null;
                entity.IND_IMPR_CT = 1;
                entity.FEC_IMPRESION_CMP = null;
                entity.FEC_IMPRESION_CT = DateTime.Now;

                BL_CompensacionVehiculo.GuardarImpresionCMPCT(entity);
                QuitarSeleccionGrilla();
                BuscarFacturas();
            }

        }

        protected void QuitarSeleccionGrilla()
        {

            for (int i = 0; i < grdFacturas.VisibleRowCount; i++)
            {

                if (grdFacturas.Selection.IsRowSelected(i))
                {
                    grdFacturas.Selection.SetSelection(i, false);

                }

            }
        }

        protected void btnSalir_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Repuestos/wFrmDefault.aspx?id=" + idNegocio);
        }

        protected void lkbVerPdf_Click(object sender, EventArgs e)
        {
            AbrirPdf();
        }

        protected void grdFacturas_PageIndexChanged(object sender, EventArgs e)
        {
            BuscarFacturas();
        }

        protected void grdFacturas_PreRender(object sender, EventArgs e)
        {
            BuscarFacturas();
        }
    
    }
}